package cn.itcast.orders.service.impl;

import cn.itcast.context.BaseContext;
import cn.itcast.orders.mapper.AddressBookMapper;
import cn.itcast.orders.pojo.AddressBook;
import cn.itcast.orders.service.AddressBookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Slf4j
public class AddressBookServiceImpl implements AddressBookService {

    @Autowired
    private AddressBookMapper addressBookMapper;

    /**
     * 新增地址
     *
     * @param addressBook
     */
    @Override
    public void add(AddressBook addressBook) {
        addressBook.setUserId(BaseContext.getCurrentId());

        if (getDefault() != null) {
            addressBook.setIsDefault(0);
        }else {
            addressBook.setIsDefault(1);
        }
        addressBookMapper.insert(addressBook);
    }

    /**
     * 查询当前登录用户的所有地址信息
     *
     * @return
     */
    @Override
    public List<AddressBook> list() {
        List<AddressBook> list = addressBookMapper.getByUserId(BaseContext.getCurrentId());
        return list;
    }

    /**
     * 查询默认地址
     *
     * @return
     */
    @Override
    public AddressBook getDefault() {
        AddressBook aDefault = addressBookMapper.getByDefault(BaseContext.getCurrentId());
        return aDefault;
    }

    /**
     * 根据id修改地址
     *
     * @param addressBook
     */
    @Override
    public void update(AddressBook addressBook) {
        addressBookMapper.update(addressBook);
    }

    /**
     * 根据id删除地址
     *
     * @param id
     */
    @Override
    public void delete(Long id) {
        addressBookMapper.delete(id);
    }

    /**
     * 根据id查询地址
     *
     * @return
     */
    @Override
    public AddressBook getById(Long id) {
        return addressBookMapper.getById(id);
    }

    /**
     * 设置默认地址
     *
     * @param id
     */
    @Transactional
    @Override
    public void setDefault(Long id) {

        addressBookMapper.update(AddressBook.builder()
                .userId(BaseContext.getCurrentId())
                .isDefault(0)
                .build());

        addressBookMapper.update(AddressBook.builder()
                .id(id)
                .isDefault(1)
                .build());
    }
}